<template>
  <div class="vet_context_menu" @contextmenu.prevent="openMenu($event)">
    <slot />
    <slot name="menuContent">
      <ul
        v-show="visible"
        :style="{ left: left + 'px', top: top + 'px' }"
        class="menu_content"
      >
        <li @click="test1">添加节点</li>
        <li @click="test2">添加节点2</li>
      </ul>
    </slot>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, watch } from "vue";
export default defineComponent({
  name: "VetContextMenu",
  setup() {
    const state = reactive({
      visible: false,
      left: 0,
      top: 0,
    });
    const test1 = () => {
      console.log("test1");
    };
    const test2 = () => {
      console.log("test2");
    };

    watch(
      () => state.visible,
      (value) => {
        if (value) {
          document.body.addEventListener("click", (event) => closeMenu());
        } else {
          document.body.removeEventListener("click", (event) => closeMenu());
        }
      }
    );

    const openMenu = (e: any) => {
      state.top = e.pageY;
      state.left = e.pageX;
      state.visible = true;
    };

    const closeMenu = () => {
      state.visible = false;
    };

    return {
      ...toRefs(state),
      test1,
      test2,
      openMenu,
      closeMenu,
    };
  },
});
</script>

<style lang="scss" scoped>
.vet_context_menu {
  display: inline-block;
  width: 50px;
  height: 50px;
  background: red;

  .menu_content {
    margin: 0;
    background: #fff;
    z-index: 3000;
    position: fixed;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    color: #333;
    box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);

    li {
      margin: 0;
      padding: 7px 16px;
      cursor: pointer;

      :hover {
        background-color: rgb(3, 125, 243);
        color: white;
      }
    }
  }
}
</style>